package org.dreamwork.jasmine2.ajax;

import org.dreamwork.jasmine2.annotation.AjaxMethod;
import org.dreamwork.jasmine2.engine.AjaxManager;
import org.dreamwork.jasmine2.engine.HttpContext;
import org.dreamwork.jasmine2.events.EventException;
import org.dreamwork.jasmine2.web.IWebControl;
import org.dreamwork.jasmine2.web.controls.WebControl;
import org.dreamwork.util.StringUtil;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;

/**
 * Created by IntelliJ IDEA.
 * User: seth.yang
 * Date: 2010-12-15
 * Time: 18:34:46
 */
public class AjaxManagerControl extends WebControl {
    private String methodList;

    public AjaxManagerControl () {
        this.viewStateEnabled = false;
        this.autoPostback = false;
    }

    public String getMethodList () {
        return methodList;
    }

    public void setMethodList (String methodList) {
        this.methodList = methodList;
    }

    @Override
    public void onPrerender (IWebControl sender, HttpContext context) throws EventException {
        if (StringUtil.isEmpty (name))
            throw new IllegalStateException ("ajax name must set!");
        StringBuilder builder = new StringBuilder ();
        if (StringUtil.isEmpty (methodList) || "*".equals (methodList.trim ())) {
            Class c = AjaxManager.get (name);
            if (c == null) return;

            Method[] ms = c.getMethods ();
            for (Method m : ms) {
                if (m.isAnnotationPresent (AjaxMethod.class)) {
                    if (builder.length () > 0) builder.append (',');
                    builder.append (m.getName ());
                }
            }
        } else {
            builder.append (methodList);
        }
        AjaxManager.registerAjaxService (this.page, name, builder.toString ());
    }

    @Override
    public void render (PrintWriter writer) throws IOException, EventException {
    }
}